
from util import ReadFile, WriteFile
import math
from xyztools import extractXYZLine
import datetime


def nrnXYZToSWC(srcFilename, sinkFilename):
    datestr = datetime.datetime.now().strftime("%d-%B-%Y")
    print " -- Converting to SWC"
    # Find the amount of translation we need to do!
    data = ReadFile(srcFilename)
    dataLines = [l for l in data.split("\n") if l.strip() and not l.strip().startswith("#") ]
    CommentLines = [l for l in data.split("\n") if l.strip and l.strip().startswith("#") ]
    
    outData = CommentLines + ["# Converted from xyz to swc using nrnXYZtoSWC.py" + " on: %s" %datestr] #["# Translated by (%d,%d,%d) using nrnTranslate.py"%translation + " On: %s"%datestr] + ["# Corrected for shrinkage (x1.28) using nrnScaled.py" + " On: %s"%datestr] + ["# Files Concatenated by nrnConcatenate.py" + " on: %s"%datestr] + ["# Converted from xyz to swc using nrnXYZtoSWC.py" + " on: %s" %datestr] 
    for l in dataLines:
        i,t,x,y,z,X,Y,Z,p = extractXYZLine(l)

        
        sX = (float(x)+float(X)) / 2.0
        sY = (float(y)+float(Y)) / 2.0
        sZ = (float(z)+float(Z)) / 2.0
            
        dX = float(x) - float(X)
        dY = float(y) - float(Y)
        dZ = float(z) - float(Z)
        d = math.sqrt( dX**2 + dY**2 + dZ**2 )
        r = d / 2.0
        r = r if r > 0.15 else 0.15
        
        outData.append( "\t".join( [str(g) for g in [i,t,sX,sY,sZ,r,p] ] ) )
    WriteFile( sinkFilename, "\n".join( outData) )
    
